const Controller=require("egg").Controller
const PageModel=require("../model/PageModel");
const MessageBox=require("../utils/MessageBox");
const appConfig=require("../../config/appConfig");
const path=require("path");
const fs=require("fs");

class GoodsInfoController extends Controller{
    async addGoodsInfo(){
        let categoryInfoList=await this.ctx.service.categoryInfo.getAllList();
        await this.ctx.render("goodsInfo/addGoodsInfo",{
            categoryInfoList
        });
    }
    async doAddGoodsInfo(){
        let file=this.ctx.request.files[0];
        if(file){
            //说明有文件
            let fileName=Date.now()+file.filename;
            let filePath=path.join(appConfig.goodsImgs,fileName);
            fs.renameSync(file.filepath,filePath);
            this.ctx.request.body.goodsimg=`/goodsImgs/${fileName}`;
        }

        let flag =await this.ctx.service.goodsInfo.addGoodsInfo(this.ctx.request.body);
        if(flag){
            await this.ctx.redirect("/goodsInfo/list");
        }
        else{
            this.ctx.body=MessageBox.alertAndBack("添加失败，请重试");
        }
    }

    async list(){
        let result = await this.ctx.service.goodsInfo.getListByPage(this.ctx.request.query);
        let categoryInfoList=await this.ctx.service.categoryInfo.getAllList();
        await this.ctx.render("goodsInfo/list",{
            goodsInfoList:result[0],
            categoryInfoList,
            pageModel:new PageModel(result[1][0].totalCount,this.ctx.request.query.pageIndex||1)
        });
    }

    async deleteGoodsInfo(){
        let cksValue=JSON.parse(this.ctx.request.query.cksValue);
        let flag =await this.ctx.service.goodsInfo.deleteGoodsInfoList(cksValue);
        this.ctx.body=flag;
    }

    async editGoodsInfo(){
        let goodsid=this.ctx.params.goodsid;
        let result =await this.ctx.service.goodsInfo.findByGoodsId(goodsid);
        let categoryInfoList=await this.ctx.service.categoryInfo.getAllList();
        if(result){
           await this.ctx.render("goodsInfo/editGoodsInfo",{
                goodsInfo:result,
                categoryInfoList
            });
        }
        else{
            this.ctx.body=MessageBox.alertAndBack("找不到数据了，请返回刷新重试");
        }
    }

    async doEditGoodsInfo(){
        let flag = await this.ctx.service.goodsInfo.editGoodsInfo(this.ctx.request.body);
        if(flag){
            this.ctx.redirect("/goodsInfo/list");
        }
        else{
            this.ctx.body=MessageBox.alertAndBack("修改失败，请返回重试");
        }
    }
}


module.exports=GoodsInfoController;